<template>
  <div class="incident-stats">
    <h1>决策树Incident分析</h1>
    <div class="filters">
      <label>年份：</label>
      <select v-model="year">
        <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
      </select>

      <label>周数：</label>
      <select v-model="selectedWeek">
        <option value="">请选择周</option>
        <option v-for="week in weeks" :key="week" :value="week">第{{ week }}周</option>
      </select>

      <label>项目：</label>
      <select v-model="project">
        <option value="">请选择项目</option>
        <option value="Shinny">Shinny</option>
        <option value="Other">Other</option>
      </select>

      <button @click="fetchData">查询</button>
    </div>

    <div ref="chartRef" class="chart-container"></div>

    <div>
      <h3>真实事件</h3>
      <table>
        <thead>
          <tr>
            <th>Inc_id</th>
            <th>Priority</th>
            <th>Short_description</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="incident in paginatedRealIncidents" :key="incident.id">
            <td>
              <!-- 将 Inc_id 列修改为可点击的链接 -->
              <router-link :to="{ name: 'IncidentDetailfortree', params: { incId: incident.Inc_id } }">
                {{ incident.Inc_id }}
              </router-link>
            </td>
            <td>{{ incident.Priority }}</td>
            <td>{{ incident.Short_description }}</td>
          </tr>
        </tbody>
      </table>
      <div class="pagination">
        <button @click="prevPage('real')">上一页</button>
        <span>第 {{ currentPageReal }} 页，共 {{ totalItemsReal }} 条</span>
        <button @click="nextPage('real')">下一页</button>
      </div>
    </div>

    <div>
      <h3>虚假事件</h3>
      <table>
        <thead>
          <tr>
            <th>Inc_id</th>
            <th>Priority</th>
            <th>Short_description</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="incident in paginatedFakeIncidents" :key="incident.id">
            <td>
              <!-- 将 Inc_id 列修改为可点击的链接 -->
              <router-link :to="{ name: 'IncidentDetailfortree', params: { incId: incident.Inc_id } }">
                {{ incident.Inc_id }}
              </router-link>
            </td>
            <td>{{ incident.Priority }}</td>
            <td>{{ incident.Short_description }}</td>
          </tr>
        </tbody>
      </table>
      <div class="pagination">
        <button @click="prevPage('fake')">上一页</button>
        <span>第 {{ currentPageFake }} 页，共 {{ totalItemsFake }} 条</span>
        <button @click="nextPage('fake')">下一页</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      year: new Date().getFullYear(), // 默认年份为当前年份
      selectedWeek: '',
      project: '',
      realIncidents: [],
      fakeIncidents: [],
      currentPageReal: 1,
      itemsPerPageReal: 10,
      currentPageFake: 1,
      itemsPerPageFake: 10,
      weeks: Array.from({ length: 53 }, (_, i) => i + 1),
      years: Array.from({ length: 10 }, (_, i) => new Date().getFullYear() - i), // 提供最近10年的选项
      chartInstance: null,
      chartData: {}
    };
  },
  computed: {
    paginatedRealIncidents() {
      const start = (this.currentPageReal - 1) * this.itemsPerPageReal;
      const end = start + this.itemsPerPageReal;
      return this.realIncidents.slice(start, end);
    },
    totalItemsReal() {
      return this.realIncidents.length;
    },
    paginatedFakeIncidents() {
      const start = (this.currentPageFake - 1) * this.itemsPerPageFake;
      const end = start + this.itemsPerPageFake;
      return this.fakeIncidents.slice(start, end);
    },
    totalItemsFake() {
      return this.fakeIncidents.length;
    },
    totalPagesReal() {
    return Math.ceil(this.totalItemsReal / this.itemsPerPageReal);
  },
  totalPagesFake() {
    return Math.ceil(this.totalItemsFake / this.itemsPerPageFake);
  }
  },
  methods: {
    async fetchData() {
      if (!this.year || !this.selectedWeek || !this.project) {
        console.warn("Please input year, week, and project before fetching data.");
        return;
      }

      try {
        const response = await axios.post('http://127.0.0.1:5000/api/classifyincidents', {
          year: this.year,
          week: this.selectedWeek,
          project: this.project
        });
        this.realIncidents = response.data.realIncidents || [];
        this.fakeIncidents = response.data.fakeIncidents || [];
        this.currentPageReal = 1;
        this.currentPageFake = 1;

        // 打印返回的分类事件数据
        console.log("Classify Incidents Response:", response.data);
      } catch (error) {
        console.error('Error fetching incidents:', error);
        this.handleError(error, 'incident');
      }

      try {
        const statsResponse = await axios.post('http://127.0.0.1:5000/api/incidentstats', {
          year: this.year,
          week: this.selectedWeek,
          project: this.project
        });
        this.chartData = statsResponse.data || {};
        console.log("Incident Stats Response:", this.chartData);

        this.initChart(); // 调用图表初始化方法
      } catch (error) {
        console.error('Error fetching incident stats:', error);
        this.handleError(error, 'stats');
      }
    },
    nextPage(type) {
      if (type === 'real' && this.currentPageReal < this.totalPagesReal) {
        this.currentPageReal++;
      } else if (type === 'fake' && this.currentPageFake < this.totalPagesFake) {
        this.currentPageFake++;
      }
    },
    prevPage(type) {
      if (type === 'real' && this.currentPageReal > 1) {
        this.currentPageReal--;
      } else if (type === 'fake' && this.currentPageFake > 1) {
        this.currentPageFake--;
      }
    },
    initChart() {
      // 提取优先级列表
      const priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low'];

      // 初始化数据数组
      const total = [];
      const closedResolved = [];
      const inProgress = [];

      // 检查 chartData 是否有效
      if (!this.chartData || Object.keys(this.chartData).length === 0) {
        console.error("Invalid or empty chartData:", this.chartData);
        return;
      }

      // 动态获取返回数据中的第一个键（例如 "2024-49" 或 "2024-48"）
      const firstKey = Object.keys(this.chartData)[0];
      const priorityData = this.chartData[firstKey]?.priorities || {};

      // 遍历优先级，提取每个优先级的数据
      priorities.forEach((priority) => {
        const data = priorityData[priority];
        total.push(data ? data.total : 0);
        closedResolved.push(data ? data.closedResolved : 0);
        inProgress.push(data ? data.inProgress : 0);
      });

      // 构建 ECharts 配置
      const option = {
        title: {
          text: '周度Incident优先级统计（决策树分类）',
          left: 'left',
          top: '10px',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: ['总数量', 'Closed/Resolved', 'Work In Progress/Open/Awaiting User Info'],
          bottom: '30px',
          textStyle: {
            fontSize: 14,
            color: '#333',
          },
        },
        xAxis: {
          type: 'category',
          data: priorities,
          axisLine: {
            lineStyle: {
              color: '#333',
            },
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#333',
            },
          },
        },
        series: [
          {
            name: '总数量',
            type: 'bar',
            data: total,
            itemStyle: {
              color: '#4CAF50',
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
            },
          },
          {
            name: 'Closed/Resolved',
            type: 'bar',
            data: closedResolved,
            itemStyle: {
              color: '#2196F3',
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
            },
          },
          {
            name: 'Work In Progress/Open/Awaiting User Info',
            type: 'bar',
            data: inProgress,
            itemStyle: {
              color: '#FF9800',
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
            },
          },
        ],
        backgroundColor: '#f9f9f9',
        grid: {
          top: '60px',
          bottom: '90px',
          left: '40px',
          right: '40px',
        },
      };

      // 设置 ECharts 配置
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      this.chartInstance = echarts.init(this.$refs.chartRef);
      this.chartInstance.setOption(option);
    },
    handleError(error, type) {
      const message = type === '获取数据失败 incident' ? 'Error fetching incidents' : 'Error fetching incident stats';
      const userMessage = `获取数据失败 Failed to fetch ${type === 'incident' ? 'incidents' : 'incident stats'}. Please check the URL and try again.`;
      console.error(message, error);
      alert(userMessage);
    }
  },
  mounted() {
    // Do not call fetchData automatically on page load
    // this.fetchData();
  }
};
</script>

<style scoped>
.incident-stats {
  font-size: 15px;
  position: relative;
  top: 0px;
  overflow-y: auto; /* 启用垂直滚动条 */
  background-color: white; /* 白色背景 */
  border-radius: 10px; /* 圆角 */
  padding: 20px; /* 内边距 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  width: 800px;
  text-align: center;
}

.filters {
  margin-top: 20px;
  margin-bottom: 20px; /* 为每个部分添加底部间距 */
}

.chart-container {
  width: 100%; /* 设置宽度为100% */
  height: 500px; /* 设置高度为500px */
  padding: 20px; /* 添加内边距以增加空间 */
  box-sizing: border-box; /* 确保内边距不会影响总宽度 */
}

/* 添加一些基本样式以美化界面 */
div {
  margin: 20px;
}

label {
  margin-right: 10px;
}

input[type="number"],
select {
  margin-right: 20px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.pagination {
  margin-top: 20px;
}

.pagination button {
  margin: 0 10px;
}

.pagination span {
  margin: 0 10px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* 新增样式：为可点击的 Inc_id 添加蓝色样式 */
a {
  color: blue; /* 设置链接颜色为蓝色 */
  text-decoration: none; /* 去掉下划线 */
}

a:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
  cursor: pointer; /* 鼠标悬停时显示手型光标 */
}
</style>